import '@wangeditor/editor/dist/css/style.css'
import {shallowRef, reactive} from "vue";
import {uploadFile} from "@/api/common";
import {getToken} from '@/utils/auth'
import { Boot } from '@wangeditor/editor'
import attachmentModule from '@wangeditor/plugin-upload-attachment'
import {Constant} from '@/utils/constant'

export default function () {
	if (Boot.plugins.length < 13) {
		//判断如果已经插入进去，不在二次插入
		Boot.registerModule(attachmentModule);
	}
	const toolbarConfig = {
        insertKeys: {
            index: 22, // 自定义插入的位置
            keys: ['uploadAttachment'], // “上传附件”菜单
        },
        excludeKeys: [
            "uploadVideo",
            "insertVideo",
            "group-video"
        ]
    }
    const editorConfig = reactive({
        placeholder: '请输入内容...',
        hoverbarKeys: {
            attachment: {
                menuKeys: ['downloadAttachment'], // “下载附件”菜单
            },
        },
        MENU_CONF: {
            uploadAttachment: {
                title: '上传附件',
                fieldName: 'fileList',
                // 超时时间，默认为 10 秒
                timeout: 100 * 1000, // 5 秒
                onSuccess(file, res) {
                    if (res.errno === 0) {
                    }
                },
                customUpload(file, insertFn) {
                    uploadFile(file).then(res => {   //upload是上传附件接口
                        insertFn(file.name, res.data[0].url)
                    })
                },
            }
        }
    })

    // 编辑器实例，必须用 shallowRef
    const editorData = shallowRef()

    const destroyEditor = () => {
        const editor = editorData.value
        if (editor == null) return
        editor.destroy()
    }

    const handleCreated = (editor) => {
        editorData.value = editor // 记录 editor 实例，重要！
        initEditorElementConfig()
    }
    const initEditorElementConfig = () => {
        const editorElementConfig = editorData.value.getMenuConfig('uploadImage')
        const editorAllConfig = editorData.value.getAllMenuKeys()
        editorElementConfig.headers = {}
        editorElementConfig.fieldName = 'fileList'
        editorElementConfig.headers['Authorization'] = 'Bearer ' + getToken()
        editorElementConfig.server = Constant.uploadUrl
        editorElementConfig.uploadAttachment = {
            async customUpload(file, insertFn) {
                uploadFile(file).then(res => {   //upload是上传附件接口
                    insertFn(file.name, res.data[0].url)
                })
            }
        }
        editorElementConfig.customInsert = (res, insertFn) => {
            // res 即服务端的返回结果
            insertFn(res.data[0].url || '', '', res.data[0] || '')
        },
            editorElementConfig.onSuccess = (file, res) => {
            }
    }

    return {
        toolbarConfig,editorConfig,editorData, handleCreated,destroyEditor
    }
}
